package com.tstudy.laoshibang.base;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.manager.CommunityMessageManager;
import com.tstudy.laoshibang.mode.CommunityMessage;
import com.tstudy.laoshibang.utils.AppShortCutUtil;
import com.tstudy.laoshibang.utils.LogUtil;
import com.tstudy.laoshibang.utils.SharedPreferencesUtil;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import de.greenrobot.event.EventBus;

@SuppressWarnings("deprecation")
public class PushGetuiReceiver extends BroadcastReceiver {
	NotificationManager mNotificationManager;
    /**
     * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView == null)
     */
    public static StringBuilder payloadData = new StringBuilder();

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.d("GetuiSdkDemo", "onReceive() action=" + bundle.getInt("action"));
        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_MSG_DATA:
                // 获取透传数据
                // String appid = bundle.getString("appid");
                byte[] payload = bundle.getByteArray("payload");
                String taskid = bundle.getString("taskid");
                String messageid = bundle.getString("messageid");
                LogUtil.d("getui taskId==" + taskid + "messageId==" + messageid);
                // smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
                boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
               String resultStr = result ? "成功" : "失败";
                LogUtil.d("getui 第三方回执接口调用" + resultStr);
//             0,活动，1，微课，2，系统消息，3 评论
//             GetuiSdkDemoreceiver payload : {"assoId":12,"bussType":2,"title":"一大帮bug来袭"}
//             {"description":"吐槽评论","title":"吐槽评论","custom_content":{"tcIsAnous":{"key":0,"text":"非匿名"},"createTime":1435220889955,"comContent":"推送","bussType":3,"tcComId":53,"tcId":29,"tcContent":"我的课什么时候上","tcUreadNum":9,"user":{"nick":"吴亚辉","imgIdxName":"","userNo":"15657403b243484280693b6f8ca3f200"},"idxes":[]}}
                if (payload != null) {
                    String data = new String(payload);
                    LogUtil.d("GetuiSdkDemo" + "receiver payload : " + data);
                    try {
						JSONObject response = new JSONObject(data);
						int bussType = response.optInt("bussType");
						int assoId = response.optInt("assoId");
						String groupId = response.optString("groupId");
						String groupName = response.optString("groupName");
						String url = response.optString("url");
						String title = response.optString("title");
						Bundle args = new Bundle();
						args.putInt(CONSTANT.ARGS.ASSO_ID, assoId);
						args.putInt(CONSTANT.ARGS.BUSS_TYPE, bussType);
						args.putString(CONSTANT.ARGS.URL, url);
						args.putString(CONSTANT.ARGS.TITLE, title);
						args.putString(CONSTANT.ARGS.GROUP_ID, groupId);
						args.putString(CONSTANT.ARGS.GROUP_NAME, groupName);
						if (bussType == CONSTANT.PUSH_BUSINESS_TYPE_COMMENT) {
							JSONObject customContentObject = response.optJSONObject("custom_content");
							if (customContentObject != null) {
								CommunityMessage communityMessage = new Gson().fromJson(customContentObject.toString(), CommunityMessage.class);
		    					CommunityMessageManager.getInstance().insertObject(communityMessage);
		    					AppShortCutUtil.addNumShortCut(context, SplashActivity.class, true, String.valueOf(communityMessage.tcUreadNum), true);
		    					EventBus.getDefault().post(communityMessage);
							}
						}else{
							mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		    		        int count = SharedPreferencesUtil.getMessageCount(context)+1;
		    		        SharedPreferencesUtil.saveMessageCount(context, count);
		    		        Notification notification = buildNotification(context,count, title, title, null,args);
		    		        mNotificationManager.notify(count, notification);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
//    				int count = SharedPreferencesUtil.getMessageCount(context)+1;
//    		        BaseApplication.mMessageCount = count;
//    		        SharedPreferencesUtil.saveMessageCount(context, count);
//    		        if (CommonUtil.isRunningForeground(BaseApplication.mContext)) {
////    		        	showMessagePop(context,count);
//    		        }
                }
                break;

            case PushConsts.GET_CLIENTID:
                // 获取ClientID(CID)
                // 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
                String clientId = bundle.getString("clientid");
                LogUtil.d("--getui clientId==" + clientId);
                if (!TextUtils.isEmpty(clientId)) {
             	   BaseApplication.mPushUserId = clientId;
             	   SharedPreferencesUtil.saveClientId(BaseApplication.mContext,BaseApplication.mPushUserId);
             	   LogUtil.d("--onbind islogin userid==" + BaseApplication.checkLogin());
             	   if (BaseApplication.checkLogin()) {
             		   HttpManager.getInstance().bindPush(true,new JsonHttpResponseHandler(){
             			@Override
             			public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
//             				BaseApplication.showToast("bind result :" + statusCode);
             				super.onSuccess(statusCode, headers, response);
             			}
             		   });	
             	   }
                }
//                if (GetuiSdkDemoActivity.tView != null) {
//                    GetuiSdkDemoActivity.tView.setText(cid);
//                }
                break;

            case PushConsts.THIRDPART_FEEDBACK:
                /*
                 * String appid = bundle.getString("appid"); String taskid =
                 * bundle.getString("taskid"); String actionid = bundle.getString("actionid");
                 * String result = bundle.getString("result"); long timestamp =
                 * bundle.getLong("timestamp");
                 * 
                 * Log.d("GetuiSdkDemo", "appid = " + appid); Log.d("GetuiSdkDemo", "taskid = " +
                 * taskid); Log.d("GetuiSdkDemo", "actionid = " + actionid); Log.d("GetuiSdkDemo",
                 * "result = " + result); Log.d("GetuiSdkDemo", "timestamp = " + timestamp);
                 */
                break;

            default:
                break;
        }
    }
    
	@SuppressLint("NewApi")
	public Notification buildNotification(Context context,int count,String title,String content,String bigContent,Bundle args){
		Notification notification;
		if(Integer.parseInt(VERSION.SDK) > 20) {
			notification = new Notification(R.drawable.logo_5,title, System.currentTimeMillis());
		}else {
			notification = new Notification(R.drawable.logo,title, System.currentTimeMillis());
		}
//		String appName = O2OApplication.getResString(R.string.app_name);
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		notification.defaults = Notification.DEFAULT_SOUND;
//		notification.number=count;
		Intent intent=new Intent(CONSTANT.MESSAGE_PUSH_NOTIFICATION_ACTION);//定义广播的动作。  
		intent.putExtra(CONSTANT.ARGS.BUNDLE, args);
		PendingIntent pi = PendingIntent.getBroadcast(context,count, intent,PendingIntent.FLAG_UPDATE_CURRENT);  
//		if(Build.VERSION.SDK_INT  >= Build.VERSION_CODES.JELLY_BEAN){
//			RemoteViews contentView = new RemoteViews(O2OApplication.mContext.getPackageName(), R.layout.notification_content_view);
//			contentView.setTextViewText(R.id.notification_content_view_content, content.toString());
//			RemoteViews bigContentView = new RemoteViews(WeicoPlusApplication.context.getPackageName(), R.layout.notification_content_view);
//			bigContentView.setTextViewText(R.id.notification_content_view_content, bigContent.toString());
//			notification.contentView = contentView;
//			notification.bigContentView = bigContentView;
//			notification.contentIntent = pi;
//		}else{
			notification.setLatestEventInfo(context, title, content, pi);
//		}
		return notification;
	}
}
